package cn.myweixin.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import cn.myweixin.po.TextMessage;
import cn.myweixin.util.CheckUtil;
import cn.myweixin.util.MessageUtil;
import cn.myweixin.util.WeixinUtil;




/**
 * Servlet implementation class weixinservlet
 * 微信接口测试
 */
@WebServlet("/weixinservlet")
public class weixinservlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
  

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String  signature=request.getParameter("signature");
		String  timestamp=request.getParameter("timestamp");
		String  nonce=request.getParameter("nonce");
		String  echostr=request.getParameter("echostr");
		PrintWriter out=response.getWriter();
		if(CheckUtil.checkSignature(signature, timestamp, nonce)){
			out.print(echostr);
		}
		out.close();
		out=null;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String message=null;
		PrintWriter out=response.getWriter();
		try{
			Map<String, String> map=MessageUtil.xmlToMap(request);
			String ToUserName=map.get("ToUserName");
			String FromUserName=map.get("FromUserName");
			String MsgType=map.get("MsgType");
			String Content=map.get("Content");
			if("text".equals(MsgType)){
				TextMessage textMessage=new TextMessage();
				textMessage.setFromUserName(ToUserName);
				textMessage.setToUserName(FromUserName);
				textMessage.setCreateTime(new Date().getTime());	
				textMessage.setMsgType(MsgType);
				if("1".equals(Content)){
				textMessage.setContent("我爸姓黄");
				}
				else if("2".equals(Content)){
					textMessage.setContent("我妈姓毛");
				}
				else if("3".equals(Content)){
					textMessage.setContent("小狗叫皮皮");
				}
                else if("4".equals(Content)){
                	textMessage.setContent("损友永子");
				}
				else{
					textMessage.setContent(WeixinUtil.getAccessToken());
					
				}
					
				message=MessageUtil.textMessageToXml(textMessage);
			}
			out.print(message);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		finally {
			out.close();
		}
	}
	
	
	

}
